package cn.itcast.wushangxiantu.BaseAdapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;

import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

import cn.itcast.wushangxiantu.Activity.LingShi;
import cn.itcast.wushangxiantu.Activity.Login;
import cn.itcast.wushangxiantu.Fragment.LingShiZhuangbei;
import cn.itcast.wushangxiantu.Fragment.LingshiChongzhu;
import cn.itcast.wushangxiantu.MessageEvent;
import cn.itcast.wushangxiantu.OkhttpUtil;
import cn.itcast.wushangxiantu.R;
import cn.itcast.wushangxiantu.ToastUtil;
import cn.itcast.wushangxiantu.UserData.User;
import cn.itcast.wushangxiantu.UserData.UserBag;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class LingShiGiveViewAdapter extends BaseAdapter {
    private Context context;
    private  UserBag.BeibaoBean lingshiBean;
    int num=0;
    User user;

    public UserBag.BeibaoBean getLingshiBean() {
        return lingshiBean;
    }

    public void setLingshiBean(UserBag.BeibaoBean lingshiBean) {
        this.lingshiBean = lingshiBean;
    }

    public LingShiGiveViewAdapter(Context context) {
        this.context = context;
    }

    @Override
    public int getCount() {
        return lingshiBean.getLingshi().size();
    }

    @Override
    public Object getItem(int i) {
        return lingshiBean.getLingshi().get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        view=View.inflate(context,R.layout.griveview_bag,null);
        ViewHolder viewHolder=new ViewHolder(view);
        viewHolder.tvName.setText(lingshiBean.getLingshi().get(i).getWpname());
        viewHolder.tvNumber.setText(lingshiBean.getLingshi().get(i).getWpnumber()+"");
        switch (lingshiBean.getLingshi().get(i).getJsdj()){
            case 1:
            case 2:
            case 3:
                viewHolder.tvName.setTextColor(ContextCompat.getColor(context, R.color.lingshi1));
                break;
            case 4:
            case 5:
            case 6:
                viewHolder.tvName.setTextColor(ContextCompat.getColor(context, R.color.lingshi2));
                break;
            case 7:
            case 8:
            case 9:
                viewHolder.tvName.setTextColor(ContextCompat.getColor(context, R.color.lingshi3));
                break;
            case 10:
            case 11:
            case 12:
                viewHolder.tvName.setTextColor(ContextCompat.getColor(context, R.color.lingshi4));
                break;
            case 13:
            case 14:
            case 15:
                viewHolder.tvName.setTextColor(ContextCompat.getColor(context, R.color.lingshi5));
                break;
            case 16:
            case 17:
            case 18:
                viewHolder.tvName.setTextColor(ContextCompat.getColor(context, R.color.lingshi6));
                break;
            case 19:
            case 20:
            case 21:
                viewHolder.tvName.setTextColor(ContextCompat.getColor(context, R.color.lingshi7));
                break;
            case 22:
            case 23:
            case 24:
                viewHolder.tvName.setTextColor(ContextCompat.getColor(context, R.color.lingshi8));
                break;
            case 25:
                viewHolder.tvName.setTextColor(ContextCompat.getColor(context, R.color.lingshi9));
                break;
        }
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                num=i;
                String hand="";
                switch (LingShi.getNum()){
                    case 0:
                        hand="重铸灵石(每次需要200魔核)";
                        break;
                    case 1:
                        hand="装备灵石";
                        break;
                }
                String content="";
                content = "灵石名称：" + lingshiBean.getLingshi().get(i).getWpname() + "\n******属性******\n" +
                        "说明：" + lingshiBean.getLingshi().get(i).getZuoyong() + "\n******装备属性******\n" +
                        "生命：" + lingshiBean.getLingshi().get(i).getJsdj() * 300 + "\n" +
                        "防御力：" + lingshiBean.getLingshi().get(i).getJsdj() * 40 + "\n" +
                        "攻击力：" + lingshiBean.getLingshi().get(i).getJsdj() * 80 + "\n" +
                        "恢复：" + lingshiBean.getLingshi().get(i).getJsdj() * 20 + "\n" +
                        "穿透：" + lingshiBean.getLingshi().get(i).getJsdj() * 20 + "\n";
                if (LingShi.getNum()==2){

                }else{
                    GeneralDialog(hand,content);
                }
            }
        });
        view.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                num=i;
                if (lingshiBean.getLingshi().get(i).getJsdj()==1){
                    ToastUtil.toast(context,"一级灵石无法分解");
                }else{
                    GeneralDialogZahuo(context,"最多分解数量为："+lingshiBean.getLingshi().get(num).getWpnumber(),num);
                }
                return false;
            }
        });
        return view;
    }

    private void getFenjie(int number) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userName=" + Login.getUser().getUsernumber()+
                "&need=fenjie"+"&number="+number+"&bag_id="+ lingshiBean.getLingshi().get(num).getBag_id(), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("fenjie1", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("fenjie2", src);
                User user =null;
                try {
                    user = new Gson().fromJson(src, User.class);
                }catch (Exception e){

                }
                Message message = new Message();
                message.obj = user;
                message.what=3;
                handler.sendMessage(message);
            }
        });
    }

    class ViewHolder {
        public View rootView;
        public TextView tvName;
        public TextView tvNumber;

        public ViewHolder(View rootView) {
            this.rootView = rootView;
            this.tvName = (TextView) rootView.findViewById(R.id.tvName);
            this.tvNumber = (TextView) rootView.findViewById(R.id.tvNumber);
        }

    }
    public void GeneralDialogXinxi(String head, String content) {
        /**
         * 普通对话框
         * 1标题
         * 2内容
         */
        AlertDialog dialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setTitle(head)

                .setMessage(content)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                });
        dialog = builder.create();
        dialog.show();
    }
    public void GeneralDialog(String head, String content) {
        /**
         * 普通对话框
         * 1标题
         * 2内容
         */
        AlertDialog dialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setTitle(head)

                .setMessage(content)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (LingShi.getNum()==0){
                            //如果重铸
                            getDataChongzhu();
                        }else{
                            //如果装备
                            getDataZhuangbei();
                        }
                    }
                });
        dialog = builder.create();
        dialog.show();
    }

    private void getDataZhuangbei() {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userName=" + Login.getUser().getUsernumber()+ "&weizhi="+ (LingShiZhuangbei.getNum()+1)+
              "&need=zhuangbeilingshi"+"&bag_id="+ lingshiBean.getLingshi().get(num).getBag_id(), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("lzzb1", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("lzzb2", src);
               User user = null;
               try {
                   user = new Gson().fromJson(src, User.class);
               }catch (Exception e){

               }
                Message message = new Message();
                message.obj = user;
                message.what=1;
                handler.sendMessage(message);
            }
        });

    }
    private void getDataChongzhu() {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userName=" + Login.getUser().getUsernumber()+
                "&need=chongzhu"+"&bag_id="+ lingshiBean.getLingshi().get(num).getBag_id(), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("chongzhu1", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("chongzhu2", src);
                User user = null;
                try {
                    user = new Gson().fromJson(src, User.class);
                }catch (Exception e){

                }
                Message message = new Message();
                message.obj = user;
                message.what=2;
                handler.sendMessage(message);
            }
        });

    }
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
           if (message.what==1){
               User user= (User) message.obj;
               if (user!=null){
                   if (user.getStw().equals("OK")){
                       MessageEvent event=new MessageEvent("LingshiZhuangbei");
                       event.setNum(lingshiBean.getLingshi().get(num).getJsdj());
                       EventBus.getDefault().post(event);//刷新灵石装备栏
                   }else{
                       ToastUtil.toast(context,user.getStw());
                   }
               }else {
                   ToastUtil.toast(context,"服务器坏掉了");
               }
           }else if (message.what==2){
               User user= (User) message.obj;
              if (user!=null){
                  try {
                      Thread.sleep(2000);
                      if (user.getStw().length()>7&&user.getDj()!=0&&user.getDj()>=6){
                          MessageEvent messageEvent=new MessageEvent("xinxi");
                          messageEvent.setContent("恭喜玩家"+Login.getUser().getName()+user.getStw());
                          EventBus.getDefault().post(messageEvent);
                      }
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
                  GeneralDialogXinxi("重铸详情",LingshiChongzhu.getContent()+"\n"+user.getStw());
              }else{
                  ToastUtil.toast(context,"服务器坏掉了");
              }
           }else if (message.what==3){
               User user= (User) message.obj;
               if (user!=null){
                   GeneralDialogXinxi("分解详情",user.getStw());
               }else {
                   ToastUtil.toast(context,"服务器坏了");
               }
           }
            EventBus.getDefault().post(new MessageEvent("Lingshi"));//刷新灵石背包
            return false;
        }
    });
    private void GeneralDialogZahuo(final Context context, String title, final int num1) {
        /**
         * 编辑框
         * 1标题
         */
        AlertDialog dialog;
        final EditText editText = new EditText(context);
        editText.setInputType(InputType.TYPE_CLASS_NUMBER);
        InputFilter[] filters = {new InputFilter.LengthFilter(9)};
        editText.setFilters(filters);
        final int content = 0;
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setTitle(title)
                .setView(editText)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (editText.getText().toString().trim().equals("")){
                            dialogInterface.dismiss();
                            ToastUtil.toast(context,"输入有误");
                            return;
                        }
                        int chushouNum=Integer.parseInt(editText.getText().toString().trim());
                        int cunzaiNum=lingshiBean.getLingshi().get(num).getWpnumber();

                        if (chushouNum ==0||chushouNum>cunzaiNum) {
                            ToastUtil.toast(context,"数量有误");
                        } else {
                            getFenjie(chushouNum);
                        }
                    }
                });
        dialog = builder.create();
        dialog.show();
    }

}
